<template>
  <van-popup
    class="popup-picker"
    :value="showPickerDlg"
    position="bottom"
    get-container="body"
    @input="(val) => onCancel()"
    @close="onCancel"
  >
    <van-picker ref="picker"
      :title="title"
      show-toolbar
      :columns="pickerColumns"
      :value-key="prop.label"
      @confirm="onConfirm"
      @cancel="onCancel"
      @change="onPickerValueChange"
    >
      <van-row class="header" slot="default" type="flex" align="cenger" justify="space-between">
        <div style="width: 116px">
          <button type="button" class="van-picker__cancel" @click="onCancel">取消</button>
        </div>
        <div class="van-ellipsis van-picker__title title">{{title}}</div>
        <van-row type="flex" justify="end" style="width: 100px; padding-right: 16px;">
          <button v-if="clearable" type="button" class="van-picker__confirm" style="padding: 0px; width: 44px;" @click="onClear">清空</button>
          <button type="button" class="van-picker__confirm" style="padding: 0px; width: 44px;" @click="onConfirm">确认</button>
        </van-row>
      </van-row>
    </van-picker>
  </van-popup>
</template>

<script>
import { findTreeNodeObjectPath, getTreeMaxLevel } from '@/utils';

export default {
  name: 'popupPicker',
  props: {
    showPickerDlg: {
      type: Boolean,
      default: false
    },
    title: {
      type: String
    },
    value: {
      type: [String, Boolean, Number, Array]
    },
    loading: {
      type: Boolean,
      default: false
    },
    treeFlag: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    dataList: {
      type: Array,
      default: () => []
    },
    prop: {
      type: Object,
      default: () => {
        return {
          value: 'id',
          label: 'name',
          children: 'children'
        }
      }
    }
  },
  data () {
    return {
      selectValue: []
    }
  },
  methods: {
    onCancel () {
      this.$emit('close');
    },
    onConfirm () {
      if (this.treeFlag) {
        let values = this.$refs.picker.getValues();
        if (Array.isArray(values) && values.length > 0) {
          this.onChange(values.filter(item => item != null).map(item => {
            return item[this.prop.value];
          }));
        } else {
          this.onChange(undefined);
        }
        this.onCancel();
      } else {
        let value = this.$refs.picker.getValues()[0];
        this.onChange(value ? value[this.prop.value] : undefined);
        this.onCancel();
      }
    },
    onChange (value) {
      this.$emit('input', value);
    },
    onClear () {
      this.onChange(undefined);
      this.$emit('close');
    },
    onPickerValueChange (owner, values, index) {
      this.selectValue = Array.isArray(values) ? values.filter(item => item != null).map(item => item[this.prop.value]) : [];
    }
  },
  computed: {
    /**
     * 获取数据最大层级
     */
    maxLevel () {
      return this.treeFlag ? getTreeMaxLevel(this.dataList, this.prop.value, this.prop.children) : 1;
    },
    /**
     * 获取picker的columns信息
     */
    pickerColumns () {
      // 获取选中值在列表中的index
      function findIndex (dataList, value, valueKey = 'id') {
        if (!Array.isArray(dataList)) return 0;
        for (let i = 0; i < dataList.length; i++) {
          if (dataList[i][valueKey] === value) return i;
        }
        return 0;
      }
      if (!Array.isArray(this.dataList)) return [];
      if (this.treeFlag) {
        // 级联选择
        let temp = this.dataList;
        let columns = [];
        for (let colIndex = 0; colIndex < this.maxLevel; colIndex++) {
          // 当前层级选中值
          let tempValue = this.selectValue[colIndex];
          // 当前层级值的indx
          let index = findIndex(temp, tempValue, this.prop.value);
          // 子级数据
          let tempChildren = temp[index] ? temp[index][this.prop.children] : undefined;
          columns.push({
            values: temp.map(item => {
              let temp = {
                ...item
              }
              temp[this.prop.children] = undefined;
              return temp;
            }),
            defaultIndex: index
          });
          // 如果没有子级数据默认使用空数组
          temp = tempChildren || [];
        }
        return columns;
      } else {
        // 列表选择
        let index = findIndex(this.dataList, this.value, this.prop.value);
        return [
          {
            values: this.dataList,
            defaultIndex: index
          }
        ]
      }
    }
  },
  watch: {
    value: {
      handler () {
        if (this.treeFlag) {
          this.selectValue = [];
          if (this.value == null || this.value === '') return;
          if (Array.isArray(this.dataList)) {
            let nodePath = findTreeNodeObjectPath(this.dataList, this.value, this.prop.value, this.prop.children);
            if (Array.isArray(nodePath)) this.selectValue = nodePath.map(item => item[this.prop.value]);
          }
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
  .popup-picker .header {
    height: 44px;
    line-height: 44px;
    width: 100%;
  }
  .popup-picker .title {
    flex-grow: 1;
    width: 50px;
    line-height: 44px;
  }
</style>
